#define _CRT_SECURE_NO_WARNINGS 1

#include "heap.h"

//TopK问题
void PrintTopK(const char*file, int k)
{
	//建堆 用a中前k个元素建小堆
	int* topk = (int*)malloc(sizeof(int) * k);
	assert(topk);

	//以读的形式打开文件
	FILE* fout = fopen(file, "r");
	if (fout == NULL)
	{
		perror("fopen error\n");
		return;
	}

	//读前k个数据
	for (int i = 0; i < k; i++)
	{
		fscanf(fout, "%d", &topk[i]);
	}

	//建小堆
	for (int i = (k - 2) / 2; i >= 0; i--)
	{
		AdjustDownMin(topk, k, i);
	}

	//将剩余n-k个元素依次与堆顶元素交换，不满则则替换
	int val = 0;
	int ret = fscanf(fout, "%d", &val);
	while (ret != EOF)
	{
		if (topk[0] < val)
		{
			topk[0] = val;
			AdjustDownMin(topk, k, 0);
		}
		ret = fscanf(fout, "%d", &val);
	}

	//打印
	for (int i = 0; i < k; i++)
	{
		printf("%d ", topk[i]);
	}
	printf("\n");

	//关闭文件
	free(topk);
	fclose(fout);
}
void CreatNData()
{
	//造数据
	int n = 10000;
	srand(time(0));

	const char* file = "data.txt";
	//以写的形式打开文件
	FILE* fin = fopen(file, "w");
	if (fin == NULL)
	{
		perror("fopen error\n");
		return;
	}

	//写文件
	for (int i = 0; i < n; i++)
	{
		int x = rand() % 10000;
		fprintf(fin, "%d\n", x);
	}

	//关闭文件
	fclose(fin);
	
}

int main()
{
	//堆的基本操作
//	HP hp;
//	HeapInit(&hp);
//
//	/*int a[] = {15,25,10,56,30,70};
//	HeapInitArray(&hp,a, 6);*/
//
//	HeapPush(&hp, 15);
//	HeapPush(&hp, 25);
//	HeapPush(&hp, 10);
//	HeapPush(&hp, 56);
//	HeapPush(&hp, 30);
//	HeapPush(&hp, 70);
//
//	int ret = HeapSize(&hp);
//	printf("%d\n", ret);
//
//	int k = 0;
//	scanf("%d", &k);
//	while (!HeapEmpty(&hp)&&k--)
//	{
//		printf("%d ", HeapTop(&hp));
//		HeapPop(&hp);
//	}
//
//	printf("\n");
//
//	HeapDestroy(&hp);
    
	//CreatNData();
    PrintTopK("data.txt", 10);

	return 0;

}